package com.mj.haier.calc.servlet.impl;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mj.haier.calc.client.FinClient;
import com.mj.haier.calc.domain.AzEorderSettlementProcess;
import com.mj.haier.calc.domain.BdGvsItemconfig;
import com.mj.haier.calc.servlet.Filter;
import com.mj.haier.calc.servlet.FilterChain;
import com.mj.haier.calc.servlet.Request;
import com.mj.haier.calc.servlet.Response;
import com.mj.haier.calc.servlet.ServletException;

public class LastLevelFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(CarsteamFilter.class);
    private final FinClient finClient;

    public LastLevelFilter(FinClient finClient){
        this.finClient = finClient;
    }

    @Override
    public void doFilter(Request req, Response res, FilterChain chain) throws IOException, ServletException {

        AzEorderSettlementProcess process = (AzEorderSettlementProcess)req.getObject();
        log.debug("LastLevelFilter 过滤前 AzEorderSettlementProcess: {}", process.toString());

        if("0".equals(process.getLevelCompliance())){
            chain.doFilter(req, res);
            return;
        }

        String sourceNameCode = process.getSourceNameCode();
        BdGvsItemconfig bdGvsItemconfig = finClient.getBdGvsItemconfig(sourceNameCode);

        process.lastLevel(bdGvsItemconfig.getDepartment())
            .lastLevelName(bdGvsItemconfig.getDepartmentName())
            .companyCode(bdGvsItemconfig.getCompanyCode())
            .sourceName(bdGvsItemconfig.getSourceName());
        
        //验证合规性
        //法人公司代码， 合规性必须; 三级小微, 合规性必须; 三级小微名称, 合规性必须
        String compliance = "0";
        StringBuilder complianceSb = new StringBuilder();
        if(StringUtils.isBlank(process.getLastLevel())){
            compliance = "1";
            complianceSb.append("三级小微编码必须, 但不合规").append("&");
        }
        if(StringUtils.isBlank(process.getLastLevelName())){
            compliance = "1";
            complianceSb.append("三级小微名称必须, 但不合规").append("&");
        }
        if(StringUtils.isBlank(process.getCompanyCode())){
            compliance = "1";
            complianceSb.append("法人公司代码必须, 但不合规").append("&");
        }

        if("0".equals(compliance)){
            complianceSb.append("末级小微与法人公司信息合规").append("&");
        }
        process.levelCompliance(compliance).levelMsg(complianceSb.toString());
        log.debug("LastLevelFilter 过滤之后 AzEorderSettlementProcess: {}", process.toString());

        chain.doFilter(req, res);
    }
}